/*
 *  ifxerror.cpp - Informix server error exception class implementation
 *
 *    Copyright (c) 2001-2006, Luxena Software Company. All rights reserved.
 *
 *  Purpose:
 *
 */

#include "ifxerror.hpp"

#include <new>
#include <stdio.h>


/////////////////////////////////////////////////////////////////////////////
// Restricted by Informix error message length

#define MAX_ERROR_MSG_LEN 0x7fff


/////////////////////////////////////////////////////////////////////////////
// CInformixServerError - exception class for Informix server error

CInformixServerError::CInformixServerError (mint sqlCode)
{
	_sqlCode = sqlCode;

	mint apiStatus;
	mint printedChars;

	// SQL error message processing
	//
	_cstr_t sqlMessage(MAX_ERROR_MSG_LEN);
	int sqlMessageLength = sprintf(sqlMessage, "%d SQL error: ", sqlCode);
	apiStatus = rgetlmsg(sqlCode, &sqlMessage[sqlMessageLength], MAX_ERROR_MSG_LEN - sqlMessageLength, &printedChars);
	if (apiStatus != 0)
		printedChars = sprintf(&sqlMessage[sqlMessageLength], "Get SQL error message failure, reason %d", apiStatus);
	sqlMessageLength += printedChars;

	// ISAM error message processing
	//
	int4 isamCode = sqlca.sqlerrd[1];
	mint isamMessageLength = 0;
	_cstr_t isamMessage;
	if (isamCode != 0)
	{
		isamMessage.attach(new char [MAX_ERROR_MSG_LEN]);
		isamMessageLength = sprintf(isamMessage, "%d ", (int) isamCode);
		apiStatus = rgetlmsg(isamCode, &isamMessage[isamMessageLength], MAX_ERROR_MSG_LEN - isamMessageLength, &printedChars);
		if (apiStatus != 0)
			printedChars = sprintf(&isamMessage[isamMessageLength], "Get ISAM error message failure, reason %d", apiStatus);
		isamMessageLength += printedChars;
	}

	// Assembly full message
	//
	char *messageFormatParameter = sqlca.sqlerrm;
	int messageLength = sqlMessageLength + isamMessageLength + 2*strlen(messageFormatParameter) + 1;
	_message.attach(new char [messageLength]);
	printedChars = sprintf(_message, sqlMessage, messageFormatParameter);
	if (isamMessageLength != 0)
		sprintf(&_message[printedChars], isamMessage, messageFormatParameter);
}
